<template>
  <!-- @close="close" 触发父组件的 close 方法 -->
  <el-dialog :visible="showDialog" title="新增部门" width="47%" @close="close">
    <el-form ref="addDept" label-width="100px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入部门名称" style="width:90%" size="mini" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入部门编码" style="width:90%" size="mini" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="managerId">
        <el-select v-model="formData.managerId" placeholder="请选择部门负责人" style="width:90%" size="mini">
          <el-option v-for="item in managerList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" type="textarea" placeholder="请输入部门介绍" style="width:90%" size="mini" />
      </el-form-item>
      <el-form-item>
        <el-row>
          <el-col :span="20">
            <el-button type="primary" size="mini" @click="btnOk">确定</el-button>
            <el-button size="mini" @click="close">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { addDepartment, getDepartment, getDepartmentDetail, updateDepartment } from '@/api/department';

export default {
  name: 'AddDept',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    // 接受父组件传来的部门id
    currentNodeId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      managerList: [],
      formData: {
        code: '',
        introduce: '',
        managerId: '',
        name: '',
        pid: ''
      },
      rules: {
        code: [{ required: true, message: '请输入部门编码', trigger: 'blur' },
        { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        {
          trigger: 'blur',
          // 自定义校验模式（验证添加的部门编码是否再已存在）
          validator: async (rule, value, callback) => {
            try {
              let result = await getDepartment();
              if (this.formData.id) {
                result = result.filter(item => item.id !== this.formData.id); // 排除当前编辑的部门
              }
              if (result.some(item => item.code === value)) {
                callback(new Error('部门编码已存在'));
              } else {
                callback();
              }
            } catch (error) {
              console.error("部门编码验证失败", error);
              callback(new Error('验证失败，请稍后再试')); // 捕获错误并提示用户
            }
          },

        }
        ],
        introduce: [{ required: true, message: '请输入部门介绍', trigger: 'blur' },
        { min: 1, max: 100, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        managerId: [{ required: true, message: '请输入人员id', trigger: 'blur' }
        ],
        name: [{ required: true, message: '请输入部门名称', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }, {
          trigger: 'blur',
          // 自定义校验模式（验证添加的部门编码是否再已存在）
          validator: async (rule, value, callback) => {
            try {
              let result = await getDepartment();
              if (this.formData.id) {
                result = result.filter(item => item.id !== this.formData.id); // 排除当前编辑的部门
              }
              if (result.some(item => item.name === value)) {
                callback(new Error('部门名称已存在'));
              } else {
                callback();
              }
            } catch (error) {
              console.error("部门名称验证失败", error);
              callback(new Error('验证失败，请稍后再试')); // 捕获错误并提示用户
            }
          },

        },
        ]
      },
    }
  },
  methods: {
    close() {
      this.$refs.addDept.resetFields() // 重置表单
      this.$emit('update:showDialog', false) // 与.sync连用
    },
    async getManagerList() {
      this.managerList = await getDepartment()
    },
    btnOk() {
      this.$refs.addDept.validate(async isOk => {
        if (isOk) {
          let msg = '新增'
          if (this.formData.id) {
            console.log(this.formData.id)
            msg = '更新'
            await updateDepartment(this.formData)
          }
          else {
            await addDepartment({ ...this.formData, pid: this.currentNodeId })
          }
          this.$emit('updateDepartment')
          this.$message.success('${msg}部门成功')
          this.close()
        }
      })
    },
    async getDepartmentDetail() {
      this.formData = await getDepartmentDetail(this.currentNodeId)
    }
  },

  created() {
    this.getManagerList()
  }
}
</script>
